#文件名: logwrite.py
import sys,time,os,random
sys.path.append('..')
from config import base

class log(object):
    __logpath = base.const.url + '/logs/'
    __logname = 'access.log'
    __today = None
    __filesize = 1 * 1024 * 1024
    __logfile = ''
    # 获取日期
    def __init__(self):
        today = time.strftime('%Y%m%d',time.localtime())
        self.__today = today
        logfile = self.__logpath + today + '/' + self.__logname
        self.__logfile = logfile
        if not os.path.exists(self.__logpath + today):
            os.makedirs(self.__logpath + today, mode=0o777)
        if not os.path.isfile(logfile):
            fd  = open(logfile,mode="w",encoding="utf-8")
            fd.close()
        else:
            pass
        return None

    def write(self,content):
        self.checklog()
        with open(self.__logfile, mode="a+", encoding="utf-8") as acc:
            acc.writelines(content+"\n")

    # 查看当前日志文件大小，若大于1M，则备份下，且重新生成日志文件
    def checklog(self):
        logsize = 0
        if not os.path.isfile(self.__logfile):
            fd = open(self.__logfile, mode="w", encoding="utf-8")
            fd.close()
        logsize = os.path.getsize(self.__logfile)
        if logsize > self.__filesize:
            newlog = time.strftime('%Y%m%d%H%M%S',time.localtime()) + '.log'
            os.rename(self.__logfile,self.__logpath + self.__today + '/' + newlog)
            os.path.isfile(self.__logfile)
            with open(self.__logfile, mode="w", encoding="utf-8"):
                pass
        else:
            pass

